package com.modificial.shiro.system.service.impl;

import com.modificial.shiro.system.dao.PermissionDao;
import com.modificial.shiro.system.domain.SysPermission;
import com.modificial.shiro.system.service.PermissionService;
import com.modificial.shiro.system.vo.PermissionTree;
import com.modificial.shiro.util.SnowFlakeGenerator;
import com.modificial.shiro.util.TreeParser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author modificial
 * @date 2018/8/5 0005
 * @company modificial_org
 * @description 权限操作
 */
@Service
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public int addPermission(SysPermission sysPermission) {
        Assert.notNull(sysPermission,"权限不能为空");
        sysPermission.setCreateTime(new Date());
        sysPermission.setUpdateTime(new Date());
        sysPermission.setPermissionId(SnowFlakeGenerator.nextId());
        return permissionDao.insert(sysPermission);
    }

    @Override
    public int updatePermission(SysPermission sysPermission) {
        Assert.notNull(sysPermission,"权限信息不能为空");
        return permissionDao.updatePermission(sysPermission);
    }

    @Override
    public int deletePermissionById(String permissionId) {
        Assert.isTrue(StringUtils.hasText(permissionId),"权限id不能为空");
        return permissionDao.deleteByPrimaryKey(permissionId);
    }

    @Override
    public SysPermission findPermissionById(String permissionId) {
        Assert.isTrue(StringUtils.hasText(permissionId),"权限id不能为空");
        return permissionDao.selectByPrimaryKey(permissionId);
    }

    @Override
    @Cacheable(key = "permissions")
    public List<PermissionTree> listPermissions() {
      List<SysPermission>list=permissionDao.selectAll();
      List<PermissionTree>permissionTrees=new ArrayList<>(list.size());
      list.forEach(it->{
          PermissionTree permissionTree=new PermissionTree();
          BeanUtils.copyProperties(it,permissionTree);
          permissionTrees.add(permissionTree);
      });
      return   TreeParser.getTreeList("1",permissionTrees);
    }
}
